import threading
# import time
import serial
import sys
import numpy as np
import matplotlib.pyplot as plt

RMax = 1000
RGrid = 100

RecTheta = 0
RecR = 0
PointUpdateFlag = 0

# ThreadLock = threading.Lock()

def chart_draw_point():
    f = plt.figure(figsize=(9, 8))
    ax = f.add_subplot(111, polar=True)
    ax.set_autoscale_on(False)
    ax.set_yticks(range(RGrid, RMax + RGrid, RGrid))
    ax.grid(True)
    plt.ion()
    while True:
        plt.pause(0.001)
        global PointUpdateFlag
        # ThreadLock.acquire()
        if PointUpdateFlag:
            PointUpdateFlag = 0
            print(RecTheta, RecR)
            ax.plot(RecTheta * 2 * np.pi / 360, RecR, 'r.')
            # ThreadLock.release()
            # time.sleep(1)

def serial_rec_data(com, bps):
    try:
        sp = serial.Serial(com, bps)
    except Exception as e:
        print('>>>serial>>>' + str(e))
    else:
        while True:
            while sp.read(1)[0] != 0xAA:
                pass
            frame = sp.read(4)
            global RecTheta, RecR, PointUpdateFlag
            # ThreadLock.acquire()
            RecTheta = frame[0] * 256 + frame[1]
            RecR = frame[2] * 256 + frame[3]
            PointUpdateFlag = 1
            # ThreadLock.release()
            # time.sleep(1)

if __name__ == '__main__':
    if len(sys.argv) > 1:
        com = 'com' + sys.argv[1]
        bps = int(sys.argv[2])
    else:
        com = 'com1'
        bps = 115200
    s = threading.Thread(target=serial_rec_data, args=(com, bps))
    c = threading.Thread(target=chart_draw_point)
    s.start()
    c.start()
    s.join()
    c.join()
